package com.example.express_auth2.service;


import com.example.express_auth2.dao.UserDao;
import com.example.express_auth2.domain.UserAuth;
import com.example.express_auth2.domain.User;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired(required = false)
    UserDao userDao;
    private final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    //根据账号返回用户信息
    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String userPhone) throws UsernameNotFoundException {
        User user = userDao.getUserBYUserPhone(userPhone);
        ArrayList<UserAuth> userAuths=userDao.findRolesByUserPhone(userPhone);
        if (user==null){
            throw new Exception();
        }
        //这哪是采用模拟
        logger.info("员工id"+user.getUserPhone());
        return changeToUser(user,userAuths);
}
    private UserDetails changeToUser(User user, ArrayList<UserAuth> userAuths){
        //权限列表，这里实际上是搞混了，数据库里存的时角色，但是这里却把角色赋予了权限，不用不影响使用
        ArrayList<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        //赋予查询到的角色
        for (UserAuth role:userAuths
        ) {
            GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(role.getUserAuthority());
            grantedAuthorities.add(grantedAuthority);
            logger.info(String.valueOf(grantedAuthority));
        }

        UserDetails userDetails= org.springframework.security.core.userdetails.User.withUsername(String.valueOf(user.getUserPhone())).password(user.getUserPassword()).authorities(grantedAuthorities).build();
        return userDetails;
    }
}
